import dayjs from 'dayjs'

/**
 * Create a logger for sequelize.
 * @author Kntt
 * @param {Object} [options]
 * @return {Function} logger
 */
function logSequelize(options) {
  let opts = options || {}
  let stream = opts.stream || process.stdout

  stream = createBufferStream(stream, 1000)

  return function logger(sql) {
    sql = sql.replace('Executing (default):', '')
    stream.write(`[SQL ${dayjs().format('HH:mm:ss')}]:${sql} \n`)
  }
}
/**
 * Create a basic buffering stream.
 * @author Kntt
 * @param {object} stream
 * @param {number} interval
 */
function createBufferStream(stream, interval) {
  var buf = []
  var timer = null

  // flush function
  function flush() {
    timer = null
    stream.write(buf.join(''))
    buf.length = 0
  }

  // write function
  function write(str) {
    if (timer === null) {
      timer = setTimeout(flush, interval)
    }

    buf.push(str)
  }

  return { write: write }
}

export default logSequelize
